package cn.xsw.handler;

import cn.xsw.common.CommonEnum;
import cn.xsw.common.MyException;
import cn.xsw.common.ResultBody;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;


/**
 * 处理业务异常
 * @author liangYiHui
 */
@ControllerAdvice
@RestController
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(value = MyException.class)
    public ResultBody myExceptionHandler(HttpServletRequest req, MyException e){
        log.error(">>>>>>>>>>>>>发生业务异常！<<<<<<<<<<<<<<<"+e.getErrorMsg());
        return ResultBody.error(e.getErrorCode(),e.getErrorMsg());
    }
    @ExceptionHandler(value = NullPointerException.class)
    public ResultBody nullPointerExceptionHandler(HttpServletRequest req,NullPointerException e){
        log.error(">>>>>>>>>>>>>发生空指针异常！<<<<<<<<<<<<<<<"+e);
        return ResultBody.error(CommonEnum.BODY_NOT_MATCH);
    }
    @ExceptionHandler(value = Exception.class)
    public ResultBody exceptionHandler(HttpServletRequest req,Exception e){
        log.error(">>>>>>>>>>>>>发生未知异常，原因是<<<<<<<<<<<<<<<"+e);
        return ResultBody.error(CommonEnum.INTERNAL_SERVER_ERROR);
    }

    @ExceptionHandler(value = MaxUploadSizeExceededException.class)
    public ResultBody maxUploadSizeExceededExceptionHandler(HttpServletRequest req,MaxUploadSizeExceededException e){
        log.error(">>>>>>>>>>>>>上传文件过大<<<<<<<<<<<<<<<"+e);
        return ResultBody.error(CommonEnum.MAX_UPLOAD_SIZE);
    }

    @ExceptionHandler(value = ExpiredJwtException.class)
    public ResultBody maxUploadSizeExceededExceptionHandler(HttpServletRequest req,ExpiredJwtException e){
        log.error(">>>>>>>>>>>>>token过期<<<<<<<<<<<<<<<"+e);
        return ResultBody.error(CommonEnum.EXPIRED_JWT);
    }
    @ExceptionHandler(value = SignatureException.class)
    public ResultBody maxUploadSizeExceededExceptionHandler(HttpServletRequest req,SignatureException e){
        log.error(">>>>>>>>>>>>>token被篡改<<<<<<<<<<<<<<<"+e);
        return ResultBody.error(CommonEnum.SIGNATURE_DISABLE);
    }
}
